package per.destiny.seckill.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import per.destiny.seckill.pojo.User;
import per.destiny.seckill.service.GoodsService;
import per.destiny.seckill.vo.GoodsVo;

import java.util.Date;

@Controller()
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @RequestMapping(value = "/toList", method = RequestMethod.GET)
    public String toList(Model model, User user) {
//        if (StringUtils.isBlank(ticket)) {
//            return "/login";
//        }
//        User user = userService.getUserByCookie(ticket, request, response);
//        if (user == null) {
//            return "/login";
//        }


        model.addAttribute("user", user);
        model.addAttribute("goodsList", goodsService.findGoodsVo());
        return "goodsList";
    }

    @RequestMapping(value = "toDetail/{goodsId}", method = RequestMethod.GET)
    public String toDetail(Model model, User user, @PathVariable("goodsId") Long goodsId) {
        model.addAttribute("user", user);
        GoodsVo goodsVo = goodsService.findGoodsVoById(goodsId);
        model.addAttribute("goods", goodsVo);

        Date startDate = goodsVo.getStartDate();
        Date endDate = goodsVo.getEndDate();
        Date now = new Date();
        // 秒杀状态
        int seckillStatus = 0;
        // 秒杀倒计时,秒
        long remainSeconds = 0;
        if (now.before(startDate)) {
            // 秒杀还未开始
            remainSeconds = (startDate.getTime() - now.getTime()) / 1000;
        } else if (now.after(endDate)) {
            // 秒杀已经结束
            seckillStatus = 2;
        } else {
            // 秒杀中
            seckillStatus = 1;
        }
        /**
         * 前端来做倒计时处理，
         * 此时前端和服务端的时间不是完全一致的，肯定会产生误差，不同的前端误差会有不同。
         * 这种场景不用考虑，因为秒杀本来就是一个看运气的场景。
         * （但是需要保证前端倒计时完毕，服务端即可秒杀，即前端的时间要迟于服务端的时间，因为有网络延迟以及代码执行时间，所以前端直接拿服务端返回的时间处理即可保证前端的时间要迟于服务端的时间），
         */
        model.addAttribute("seckillStatus", seckillStatus);
        model.addAttribute("remainSeconds", remainSeconds);
        return "goodsDetail";
    }
}
